package com.qding.park.manager.web.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qding.park.common.core.annotation.log.OperationLogType;
import com.qding.park.common.core.annotation.log.SystemControllerLog;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.system.SystemUnKnown;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.export.DataField;
import com.qding.park.common.utils.export.ExportDataSource;
import com.qding.park.common.utils.export.excel.ExcelDataExportor;
import com.qding.park.common.utils.export.excel.MODE;
import com.qding.park.common.web.controller.BaseController;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.common.rest.domain.AnswerMsg;
import com.qding.park.manager.common.rest.domain.AnswerMsgFactoryImpl;
import com.qding.park.manager.common.rest.enums.ResponseCodeEnum;
import com.qding.park.manager.facade.statis.service.MonthStatisFacade;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.example.NcMonthRentExample;
import com.qding.park.manager.pojo.noncore.NcMonthRent;
import com.qding.park.manager.web.form.MonthListForm;
import com.qding.park.manager.web.power.Power;

/**
 * @ClassName: Web_MonthRentOrderController
 * @Description: 月租续费单统计
 * @author Comsys-Administrator
 * @date 2016年10月11日 上午11:40:26
 *
 */
@RestController
@RequestMapping("/monthRentOrder")
public class Web_MonthRentOrderController extends BaseController {
    private static final Logger _log = LoggerFactory.getLogger(Web_MonthRentOrderController.class);

	
	/**
	  * @Fields monthStatisFacade : TODO（月租单统计）
	  */
	@Autowired
	private MonthStatisFacade   monthStatisFacade;
	
	/**
	  * list(月租续费单统计单)
	  * TODO(这里描述这个方法适用条件 – 可选)
	  * TODO(这里描述这个方法的执行流程 – 可选)
	  * TODO(这里描述这个方法的使用方法 – 可选)
	  * TODO(这里描述这个方法的注意事项 – 可选)
	  * @Title: list
	  * @Description: TODO
	  * @param @param payStartTime  缴费开始时间
	  * @param @param payEndTime   缴费结束时间
	  * @param @param carNum        车牌号
	  * @param @param parkId       当前位置
	  * @param orderSource  订单来源
	  * @param @param jumpPage      当前页码
	  * @param @param pageLength     每页长度
	  * @param @return    设定文件
	  * @return AnswerMsg    返回类型
	  * @throws
	  */
	@Power(visitPark = "#form.getParkId()")
	@SystemControllerLog(description="月租单查询",operation=OperationLogType.monthRent_list)
	@RequestMapping("/list")
	public AnswerMsg list(@Valid  MonthListForm form,BindingResult result) {
			
			/* 解析验证结果 */
			super.analysisValid(result);
			/* 解析验证结果 */
			
			PowerInfo power = this.getPowerInfo();
			
			
			int jumpPageInt = Integer.valueOf(form.getJumpPage());
			int pageLengthInt = Integer.valueOf(form.getPageLength());
			
			/*组装统计条件*/
			
			NcMonthRentExample example=new NcMonthRentExample();
			if (!StringUtils.isBlank(form.getPayStartTime())) {
				// 缴费开始时间
				example.setPayStartTime(DateUtils.parseDate(form.getPayStartTime(), DateUtils.DATE_FORMAT_DATETIME));
//				example.setPayStartTime(DateUtils.parseDate(payStartTime, DateUtils.DATE_FORMAT_DATETIME));
			}
			if (!StringUtils.isBlank(form.getPayEndTime())) {
				// 缴费开始时间
				example.setPayEndTime(DateUtils.parseDate(form.getPayEndTime(),DateUtils.DATE_FORMAT_DATETIME));
//				criteria.andPaytimeLessThanOrEqualTo(DateUtils.parseDate(payEndTime, DateUtils.DATE_FORMAT_DATETIME));
			}
			
			if (!StringUtils.isBlank(form.getCarNum())) {
				// 车牌号
//				criteria.andCarnumEqualTo(carNum);
				example.setCarNum(form.getCarNum());
			}
			if (!StringUtils.isBlank(form.getOrderSource())) {
				// 支付渠道
				example.setOrderSource(form.getOrderSource());
			}
			if (!StringUtils.isBlank(form.getParkId())) {
				// 车场编号
				example.setParkId(form.getParkId());
			}
			
			if(!power.isAdminIs()){
				example.setInParks(power.getParkList());
			}
			
			/*组装统计条件*/
			
			/*****统计查询*******/
			ParkDataResult dataResult = monthStatisFacade.list(example, jumpPageInt, pageLengthInt);
			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
			return answerMsg;
	}
	
	@Power(visitPark = "#parkId")
	@SystemControllerLog(description="月租单导出",operation=OperationLogType.monthRent_exportExcel)
	@RequestMapping("/exportExcel")
	@ResponseBody
	public AnswerMsg exportExcel(String payStartTime, String payEndTime,String parkId) {
			
		try {
			PowerInfo power = this.getPowerInfo();
			
			final NcMonthRentExample example=new NcMonthRentExample();
			
			if (!StringUtils.isBlank(payStartTime)) {
				example.setPayStartTime(DateUtils.parseDate(payStartTime,DateUtils.DATE_FORMAT_DATETIME));
				// 缴费开始时间
//				criteria.andPaytimeGreaterThanOrEqualTo(DateUtils.parseDate(payStartTime, DateUtils.DATE_FORMAT_DATETIME));
			}
			if (!StringUtils.isBlank(payEndTime)) {
				example.setPayEndTime(DateUtils.parseDate(payEndTime,DateUtils.DATE_FORMAT_DATETIME));
				// 缴费开始时间
//				criteria.andPaytimeLessThanOrEqualTo(DateUtils.parseDate(payEndTime, DateUtils.DATE_FORMAT_DATETIME));
			}
			if(!StringUtils.isBlank(parkId)){
				example.setParkId(parkId);
			}
			if(!power.isAdminIs()){
				example.setInParks(power.getParkList());
			}
			
			final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
			String filename = "月租缴费单报表_" + sdf2.format(new Date());
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
			OutputStream os = response.getOutputStream();
			DataField[] dataFields = new DataField[8];
			dataFields[0] = new DataField("订单号", "orderId",30);
			dataFields[1] = new DataField("订单状态", "orderStatus",35);
			dataFields[2] = new DataField("用户账号", "tel", 20);
			dataFields[3] = new DataField("续费车牌", "carNum", 25);
			dataFields[4] = new DataField("续费车场", "parkName", 30);
			dataFields[5] = new DataField("续费类型", "payType",20);
			dataFields[6] = new DataField("续费金额(元)", "receivedFee",20);
			dataFields[7] = new DataField("到期时间", "monthlyEndTime",20);
			
			
			new ExcelDataExportor<Object>(dataFields, new ExportDataSource<Object>() {
				@Override
				public List getData(){
					// 查询统计条件
					List<NcMonthRent>  monthList=monthStatisFacade.exportExcel(example);
					List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
						int temp = 0;
						for (int i = 0; i < monthList.size(); i++) {
							Map<String, Object> mapParam = new HashMap<String, Object>();
							NcMonthRent month=monthList.get(i);
							temp=i;
							mapParam.put("orderId",month.getPayOrderID());
							mapParam.put("orderStatus", DateUtils.formatDate(month.getCreate_date(),DateUtils.DATE_FORMAT_DATETIME)+" 成功");
							mapParam.put("tel",month.getTel());
							mapParam.put("carNum", month.getCarNum());
							mapParam.put("parkName", month.getParkName());
							mapParam.put("payType",OrderSourceEnum.getDescByCode(month.getOrderSource()));
							mapParam.put("receivedFee", month.getPaymentAmount()/100);
							mapParam.put("monthlyEndTime",  month.getMonthlyEndTime()==null?"":DateUtils.formatDate(month.getMonthlyEndTime(),DateUtils.DATE_FORMAT_DATEONLY));
							lists.add(mapParam);
						}
					return lists;
				}
			}, os, MODE.EXCEL).export();
			
			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(null);
			return answerMsg;
		} catch (Exception e) {
			SystemUnKnown ex = new SystemUnKnown(e, ExceptionMessage.createExceptionMessage(SystemUnKnown.default_Name,
					"未知Exception", "payStartTime=" + payStartTime + ",payEndTime=" + payEndTime));
			exceptionHandle.handle(ex);
			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createErrorAnserMsg(ResponseCodeEnum.SYSTEM_ERROR);
			return answerMsg;
		}
	}
}
